package com.kevin.springboot.demos.handler;

import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Image;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.io.InputStream;

import static com.google.common.io.ByteStreams.toByteArray;

/**
 * 页脚
 * @author: wangyong
 * @date: 2019/8/18 0:29
 */
public class PdfFooterEvent implements IEventHandler {

	protected PdfFormXObject placeholder;
	protected float x = 500f;
	protected float y = 280f;
	protected float imageWidth = 166;
	protected float imageHeight = 166;
	protected float space = 10f;
	public PdfFooterEvent() {
		placeholder =
				new PdfFormXObject(new Rectangle(0, 0, 500, 78));
	}

	@Override
	public void handleEvent(Event event) {
		PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
		PdfDocument pdf = docEvent.getDocument();
		PdfPage page = docEvent.getPage();
		Rectangle pageSize = page.getPageSize();
		PdfCanvas pdfCanvas = new PdfCanvas(
				page.getLastContentStream(), page.getResources(), pdf);
		pdfCanvas.addXObject(placeholder, x + space, y);
		Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
		ImageData image = null;
		InputStream buleRed = null;
		try {
			buleRed=new ClassPathResource("/static/images/seal.png").getInputStream();
			image = ImageDataFactory.create(toByteArray(buleRed));
		} catch (IOException e) {
			e.printStackTrace();
		}
		Image img = new Image(image);
		img.scaleAbsolute(imageWidth, imageHeight);
		img.setFixedPosition(x, y);
		canvas.add(img);
		pdfCanvas.release();
	}

}
